
const http = require('http');
const url = require('url');
const fs = require('fs');
// 读出文件
function read(data,cb) {
  fs.readFile(data,'utf-8',function (err,data) {
    if(err || data.length == 0){  // 如果是错误或者长度0返回空
      cb([])
    }else{
      cb(JSON.parse(data))  // 将读出的转成对象
    }
  })
}

http.createServer((req,res)=>{
  // 解决跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("X-Powered-By",' 3.2.1');
  if(req.method=="OPTIONS"){
    return res.end(); /*让options请求快速返回*/
  }
  let {pathname,query} = url.parse(req.url,true); // 加true把query
  // 首页接口
  if(pathname === '/data'){
    read('./index.json',function (datas) {
      res.setHeader('Content-Type','application/json;charset=utf-8');
      res.end(JSON.stringify(datas))
    });
    return
  };

  if(pathname === '/list'){
    read('./city.json',function (list) {
      res.setHeader('Content-Type','application/json;charset=utf-8');
      res.end(JSON.stringify(list))
    });
    return
  }
}).listen(3000, "192.168.99.38");
